﻿using System;
using Newtonsoft.Json;

namespace Best.SmartCms.Utility.JsonFormater
{
    /// <summary>
    /// 
    /// </summary>
    public class CustomizeGuidConverter : JsonConverter
    {
        /// <inheritdoc />
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            try
            {
                if (value == null || Guid.Parse(value.ToString()).Equals(Guid.Empty))
                {
                    writer.WriteValue("");
                }
                else
                {
                    writer.WriteValue(value);
                }
            }
            catch (Exception)
            {
                writer.WriteValue("");
            }
        }

        /// <inheritdoc />
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
            JsonSerializer serializer)
        {
            return Guid.TryParse(reader.Value?.ToString(), out var value) ? value : Guid.Empty;
        }


        /// <inheritdoc />
        public override bool CanConvert(Type objectType)
        {
            return true;
        }
    }
}
